<template>
    <el-dialog :title="title" custom-class="el-dialog-600" v-model="visible">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
            <el-form-item label="用户名" prop="account">
                <el-col :span="23">
                    <el-input
                        clearable
                        v-model="form.account"
                        :disabled="id ? true : false"
                        placeholder="请输入用户名"
                    />
                </el-col>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="!id">
                <el-col :span="23">
                    <el-input
                        type="password"
                        clearable
                        v-model="form.password"
                        placeholder="请输入密码"
                    />
                </el-col>
            </el-form-item>
            <el-form-item label="角色" prop="role_id">
                <el-select v-model="form.role_id" clearable placeholder="请选择用户角色">
                    <el-option
                        v-for="item in roleList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="手机" prop="phone">
                <el-col :span="23">
                    <el-input clearable v-model="form.phone" />
                </el-col>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-col :span="23">
                    <el-input clearable v-model="form.name" />
                </el-col>
            </el-form-item>
            <el-form-item label="Email" prop="email">
                <el-col :span="23">
                    <el-input clearable v-model="form.email" />
                </el-col>
            </el-form-item>
            <el-form-item label="头像" prop="avatarUrl">
                <Uploader
                    v-model="form.avatarUrl"
                    :on-success="thumbUpload"
                    :on-remove="removeThumbUpload"
                />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-col :span="23">
                    <el-radio
                        clearable
                        v-model="form.status"
                        v-for="item in statusRadio"
                        :key="item.id"
                        :label="item.id"
                    >
                        {{ item.name }}
                    </el-radio>
                </el-col>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible = false"> 取 消 </el-button>
            <el-button type="primary" :loading="loading" @click="onSubmit"> 确 定 </el-button>
        </template>
    </el-dialog>
</template>

<script>
import { getCurrentInstance, ref, reactive, watch } from 'vue';
import Options from '@/global/local-data/system';
import { adminUser as Api } from 'api';

export default {
    setup() {
        const { proxy } = getCurrentInstance();

        // 手机号验证
        const checkPhone = (rule, value, callback) => {
            if (proxy.$validate.isPhone(value) || value == '') {
                callback();
            } else {
                return callback(new Error('请输入正确的手机号'));
            }
        };
        // 电子邮件验证
        const checkEmail = (rule, value, callback) => {
            if (proxy.$validate.isEmail(value) || value == '') {
                callback();
            } else {
                return callback(new Error('请输入正确的电子邮件'));
            }
        };

        let id = ref(null); // 用户id
        let loading = ref(false); //等待按钮
        let visible = ref(false); //弹窗开关
        let title = ref(null); // 标题
        let roleList = reactive([]); // 角色列表
        let statusRadio = Options.user.statusRadio;

        // 表单
        let form = reactive({
            account: '',
            password: '',
            name: '',
            avatarUrl: '',
            email: '',
            phone: '',
            role_id: '',
            status: 0
        });
        // 验证
        let rules = {
            role_id: [{ required: true, message: '请选择角色', trigger: 'change' }],
            account: [
                { required: true, message: '请输入用户名', trigger: 'change' },
                { min: 5, max: 12, message: '长度5到12个字符', trigger: 'change' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'change' },
                { min: 8, max: 16, message: '长度8到16个字符', trigger: 'change' }
            ],
            phone: [
                { required: true, message: '请输入手机号码', trigger: 'change' },
                { validator: checkPhone, trigger: 'change' }
            ],
            name: [{ required: true, message: '请输入用户名', trigger: 'change' }],
            email: [{ validator: checkEmail, trigger: 'change' }]
        };

        // 初始化
        const init = () => {
            title.value = id.value ? '编辑' : '新增';

            getRoleList();

            if (id.value) getById();
        };
        // 获取角色列表
        const getRoleList = async () => {
            const { code, data } = await proxy.$http.get(Api.getRoleList);
            if (code === 200) {
                data.forEach((item, index) => {
                    roleList[index] = item;
                });
            }
        };
        // 获取详情
        const getById = async () => {
            const { code, data } = await proxy.$http.get(Api.getById, {
                params: { id: id.value }
            });

            if (code === 200) {
                form.role_id = data.role_id;
                form.account = data.account;
                form.phone = data.phone;
                form.avatarUrl = data.avatar || '';
                form.email = data.email || '';
                form.status = data.status;
                form.name = data.name;
            }
        };
        // 图片上传
        const thumbUpload = (fileStr) => {
            form.avatarUrl = fileStr;
        };
        // 图片删除
        const removeThumbUpload = (fileStr) => {
            form.avatarUrl = fileStr;
        };
        // 提交表单
        const onSubmit = async () => {
            await proxy.$refs['formRef'].validate((valid) => {
                if (valid) {
                    loading.value = true;
                }
            });
            if (loading.value) {
                let url = id.value ? Api.update : Api.add;
                let params = {
                    role_id: form.role_id,
                    account: form.account,
                    password: form.password,
                    name: form.name,
                    avatarUrl: form.avatarUrl,
                    email: form.email,
                    phone: form.phone,
                    status: form.status
                };

                if (id.value) params.id = id.value;

                const { code, msg, data } = await proxy.$http.post(url, params);

                if (code === 200) {
                    proxy.$msg.success(msg);
                    proxy.$parent.getList();

                    visible.value = false;
                } else {
                    proxy.$msg.error(msg ? msg : data);
                }

                loading.value = false;
            }
        };
        // 监听窗口开关
        watch(visible, (newVal, oldVal) => {
            newVal ? init() : proxy.$refs['formRef'].resetFields();
        });

        return {
            id,
            loading,
            visible,
            title,
            roleList,
            statusRadio,
            form,
            rules,
            thumbUpload,
            removeThumbUpload,
            onSubmit
        };
    }
};
</script>